<template>
  <div>
    <a-card :bordered="true">
      <f-search-form :more="true" @searchHandler="searchHandler">
        <f-search-form-item label="项目编码" name="projectCode" slot="advanced" />
        <f-search-form-item label="项目名称" name="projectName" />
        <f-search-form-item label="工程包号" name="packageNo" slot="advanced" />
        <f-search-form-item label="工程包名称" name="packageName" slot="advanced" />
        <f-search-form-item label="材料申请明细编码" name="purchaseDetailsId" slot="advanced" />
        <f-search-form-item label="材料申请人" name="userName" slot="advanced" />
        <f-search-form-item label="班组" name="supplierName" slot="supplierName" />
        <f-search-form-item label="预留号" name="reserveNo" slot="advanced" />
        <f-search-form-item label="预留行号" name="reserveRow" slot="advanced" />
        <f-search-form-item label="材料WBS代码" name="materialWbsCode" slot="advanced" />
        <f-search-form-item label="物料代码" name="materialCode" slot="advanced" />
        <f-search-form-item label="设备、材料名称" name="materialName" slot="advanced" />
        <!-- <f-search-form-item label="型号/规格" name="materiaSpecs" slot="advanced" /> -->
        <f-search-form-item label="项目名称" name="materiaSpecs" slot="advanced" />
        <f-search-form-item label="技术参数或技术说明" name="technicalData" slot="advanced" />
        <f-search-form-item label="层级号" name="levelNo" slot="advanced" />
        <f-search-form-item label="区域" name="materialArea" slot="advanced" />
        <f-search-form-item label="系统" name="materialUse" slot="advanced" />
        <f-search-form-item label="计量单位" name="measurementUnit" slot="advanced" />
      </f-search-form>
      <f-table
        ref="table"
        rowKey="purchaseDetailsId"
        :columns="columns"
        :exportBtn="false"
        :multiple="false"
        :operator="operator"
        :params="queryParam"
        :api="api.recDeliReq"
        bordered
        :scroll="{ x: 1300, y: 500 }"
        :dataSource="dataSource"
        :customHeaderRow="customHeaderCellFun"
        :showSetting="true"
               :showTotal="false"
               :tableColumns="columns"
      >
        <!-- 编辑 -->
        <template v-for="col in editSlots" :slot="col" slot-scope="text, record, index" :row-selection="rowSelection">
          <div :key="col">
            <a-input
              v-if="editingKey === record.purchaseDetailsId && col === 'recNumThis'"
              style="margin: -5px 0; background-color: #ffedd9"
              :value="text"
              @change="(e) => handleChange(e.target.value, record.purchaseDetailsId, col, record)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <template>
            <a-tag v-if="'' === record.reserveNo"> 平衡利库中 </a-tag>
            <a-tag v-else-if="'' !== record.reserveNo && 0 === record.receiveNum"> 送货中 </a-tag>
            <span v-else-if="editingKey === record.purchaseDetailsId">
              <a @click="() => edit(record, record.purchaseDetailsId)">OK</a>
            </span>
            <span v-else>
              <a @click="() => edit(record, record.purchaseDetailsId)">领料</a>
            </span>
          </template>
        </template>

        <span slot="createTime" slot-scope="createTime">
          {{ createTime | format }}
        </span>
        <!--  -->
        <a-tag
          v-if="recNumThisSum !== '0' && '' != recNumThisSum"
          color="green"
          slot="recNumThisSum"
          slot-scope="recNumThisSum"
        >
          {{ recNumThisSum }}
        </a-tag>
        <a-tag v-else slot="recNumThisSum" slot-scope="recNumThisSum">
          {{ recNumThisSum }}
        </a-tag>

        <a-tag v-if="recNumFish !== '0' && '' != recNumFish" color="green" slot="recNumFish" slot-scope="recNumFish">
          {{ recNumFish }}
        </a-tag>
        <a-tag v-else slot="recNumFish" slot-scope="recNumFish">
          {{ recNumFish }}
        </a-tag>

        <a-tag
          v-if="recNumSurplus !== '0' && '' != recNumSurplus"
          color="green"
          slot="recNumSurplus"
          slot-scope="recNumSurplus"
        >
          {{ recNumSurplus }}
        </a-tag>
        <a-tag v-else slot="recNumSurplus" slot-scope="recNumSurplus">
          {{ recNumSurplus }}
        </a-tag>
      </f-table>
      <brdv-drawer ref="drawer"></brdv-drawer>
    </a-card>
    <div v-if="visible">
      <a-modal
        title="出库班组选择"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <span>项目名称：</span>
        <a-select
          style="width: 400px; margin-bottom: 15px"
          showSearch
          optionFilterProp="children"
          @change="valueChange"
        >
          <a-select-option v-for="item in projectList" :key="item.projectId" :value="item.projectId">
            {{ item.projectName }}
          </a-select-option>
        </a-select>
        <span>专业分类：</span>
        <a-select
          style="width: 400px; margin-bottom: 15px"
          showSearch
          optionFilterProp="children"
          v-model="majorCodeSeleted"
          @change="valueChangeMajor"
        >
          <a-select-option v-for="item in majorList" :key="item.majorCode" :value="item.majorCode">
            {{ item.majorName }}
          </a-select-option>
        </a-select>
        <span>工程包：</span>
        <a-select
          style="width: 400px; margin-bottom: 15px; margin-left: 14px"
          showSearch
          optionFilterProp="children"
          v-model="packageCodeSeleted"
          @change="valueChangePackage"
        >
          <a-select-option v-for="item in packageList" :key="item.packageCode" :value="item.packageCode">
            {{ item.packageName }}
          </a-select-option>
        </a-select>
        <span>供应商：</span>
        <a-select style="width: 400px; margin-bottom: 15px; margin-left: 14px" showSearch optionFilterProp="children" v-model="supplierCodeSeleted">
          <a-select-option
            v-for="item in supplierList"
            :key="item.supplierCode"
            :value="item.supplierCode"
          >
            {{ item.supplierName }}
          </a-select-option>
        </a-select>
      </a-modal>
    </div>
  </div>
</template>
<script>
import brdvDrawer from './recDeliReq_drawer.vue'
import moment from 'moment'
import api from './js/api'
import apiBmp from '../bmp/js/api'
import { formatDate } from '../common/data'
import { axios } from '../../../../utils/request'

// const data = [];
export default {
  name: 'TableList',
  components: {
    brdvDrawer,
  },
  data() {
    const me = this
    //操作按钮
    const operator = []
    operator.push({
      name: '出库提交',
      icon: 'check-circle',
      that: this,
      handler: function (table, that) {
        if(that.delivery_chk(that.dataSource)) {
          that.visible = true
        } else {
          that.visible = false
        }
      },
    })
    return {
      projectId: '',
      majorCodeSeleted: '',
      packageCodeSeleted: '',
      supplierCodeSeleted: '',
      projectList: [],
      majorList: [],
      packageList: [],
      supplierList: [],
      visible: false,
      confirmLoading: false,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      api: Object.assign(api, this.api),
      apiBmp: Object.assign(apiBmp, this.apiBmp),
      editingKey: '',
      purchaseDetailsId: '',
      //列表初始化查询参数
      queryParam: {},
      // 表头
      columns: [
        // 项目基础信息
        {
          title: '项目基础信息',
          align: 'center',
          // customHeaderCell: this.cell1890ff,
          children: [
            {
              title: '项目编码',
              align: 'center',
              dataIndex: 'projectCode',
              width: 120,
              sorter: (a, b) => a.projectCode.length - b.projectCode.length,
            },
            // {
            //   title: '项目名称',
            //   align: 'center',
            //   dataIndex: 'projectName',
            //   width: 190,
            //   sorter: (a, b) => a.projectName.length - b.projectName.length,
            // },
            // {
            //   title: '专业代码',
            //   align: 'center',
            //   dataIndex: 'majorCode',
            //   width: 100,
            //   sorter: (a, b) => a.majorCode.length - b.majorCode.length,
            // },
            // {
            //   title: '专业名称',
            //   align: 'center',
            //   dataIndex: 'majorName',
            //   width: 100,
            //   sorter: (a, b) => a.majorName.length - b.majorName.length,
            // },
            {
              title: '工程包代码',
              align: 'center',
              dataIndex: 'packageNo',
              width: 100,
              sorter: (a, b) => a.packageNo.length - b.packageNo.length,
            },
            // {
            //   title: '工程包名称',
            //   align: 'center',
            //   dataIndex: 'packageName',
            //   width: 130,
            //   sorter: (a, b) => a.packageName.length - b.packageName.length,
            // },
          ],
        },
        // 物资信息
        {
          title: '物资信息',
          align: 'center',
          children: [
            {
              title: '设备、材料名称',
              align: 'center',
              dataIndex: 'materialName',
              width: 200,
              sorter: (a, b) => a.materialName.length - b.materialName.length,
            },
            // {
            //   title: '型号/规格',
            //   align: 'center',
            //   dataIndex: 'materiaSpecs',
            //   width: 100,
            //   sorter: (a, b) => a.materiaSpecs.length - b.materiaSpecs.length,
            // },
            // {
            //   title: '项目名称',
            //   align: 'center',
            //   dataIndex: 'materiaSpecs',
            //   width: 100,
            //   sorter: (a, b) => a.materiaSpecs.length - b.materiaSpecs.length,
            // },
            {
              title: '技术参数或技术说明',
              align: 'center',
              dataIndex: 'technicalData',
              width: 200,
              sorter: (a, b) => a.technicalData.length - b.technicalData.length,
            },
            // {
            //   title: '层级号',
            //   align: 'center',
            //   dataIndex: 'levelNo',
            //   width: 120,
            //   sorter: (a, b) => a.levelNo.length - b.levelNo.length,
            // },
            {
              title: '区域',
              align: 'center',
              dataIndex: 'materialArea',
              width: 100,
              sorter: (a, b) => a.materialArea.length - b.materialArea.length,
            },
            {
              title: '系统',
              align: 'center',
              dataIndex: 'materialUse',
              width: 120,
              sorter: (a, b) => a.materialUse.length - b.materialUse.length,
            },
            {
              title: '计量单位',
              align: 'center',
              dataIndex: 'measurementUnit',
              width: 120,
              sorter: (a, b) => a.measurementUnit.length - b.measurementUnit.length,
            },
          ],
        },
        // 物资申请明细
        {
          title: '物资申请明细',
          align: 'center',
          children: [
            {
              title: '材料申请明细编码',
              align: 'center',
              dataIndex: 'purchaseDetailsId',
              width: 180,
              sorter: (a, b) => a.purchaseDetailsId.length - b.purchaseDetailsId.length,
            },
            {
              title: '材料申请时间',
              align: 'center',
              dataIndex: 'createTime',
              width: 120,
              scopedSlots: { customRender: 'createTime' },
              sorter: (a, b) => a.createTime.length - b.createTime.length,
            },
            {
              title: '已采购数量',
              align: 'center',
              dataIndex: 'purchaseNum',
              width: 120,
              sorter: (a, b) => a.purchaseNum.length - b.purchaseNum.length,
            },
            {
              title: '在途数量',
              align: 'center',
              dataIndex: 'onLineNum',
              width: 120,
              sorter: (a, b) => a.onLineNum.length - b.onLineNum.length,
            },
            {
              title: '到货数量',
              align: 'center',
              dataIndex: 'receiveNum',
              width: 120,
              sorter: (a, b) => a.receiveNum.length - b.receiveNum.length,
            },
            {
              title: '班组',
              align: 'center',
              dataIndex: 'supplierName',
              width: 120,
              sorter: (a, b) => a.supplierName.length - b.supplierName.length,
            },
            // {
            //   title: '预留号',
            //   align: 'center',
            //   dataIndex: 'reserveNo',
            //   width: 120,
            //   sorter: (a, b) => a.reserveNo.length - b.purchaseDetailsId.length,
            // },
            // {
            //   title: '预留行号',
            //   align: 'center',
            //   dataIndex: 'reserveRow',
            //   width: 120,
            //   sorter: (a, b) => a.reserveRow.length - b.reserveRow.length,
            // },
          ],
        },
        // 领料申请明细
        {
          title: '领料申请明细',
          align: 'center',
          children: [
            {
              title: '已申请量',
              align: 'center',
              dataIndex: 'recNumThisSum',
              width: 120,
              scopedSlots: { customRender: 'recNumThisSum' },
              sorter: (a, b) => a.recNumThisSum.length - b.recNumThisSum.length,
            },
            {
              title: '已出库量',
              align: 'center',
              dataIndex: 'recNumFish',
              width: 120,
              scopedSlots: { customRender: 'recNumFish' },
              sorter: (a, b) => a.recNumFish.length - b.recNumFish.length,
            },
            {
              title: '可领料量',
              align: 'center',
              dataIndex: 'recNumSurplus',
              width: 120,
              scopedSlots: { customRender: 'recNumSurplus' },
              sorter: (a, b) => a.recNumSurplus.length - b.recNumSurplus.length,
            },
            {
              title: '本次领料量',
              align: 'center',
              dataIndex: 'recNumThis',
              scopedSlots: {
                customRender: 'recNumThis',
              },
              width: 120,
              sorter: (a, b) => a.recNumThis.length - b.recNumThis.length,
            },
          ],
        },
        {
          title: '操作',
          align: 'center',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      dataSource: [],
      editSlots: ['recNumThis'],
      operator: operator,
    }
  },
  created() {
    this.getProjectList()
  },
  filters: {
    format(time) {
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
  },
  methods: {
    // handleShow(materialPlanId) {
    //   this.queryParam.materialPlanId = materialPlanId
    //   this.modalVisible = true
    //   this.$refs.table.refresh()
    // },
    edit(record, key) {
      if (this.editingKey === key) {
        this.editingKey = ''
      } else {
        this.editingKey = key
      }
    },
    handleChange(value, key, column, record) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => key === item.purchaseDetailsId)[0]
      record[column] = value

      if (target) {
        newData['purchaseDetailsId'] = key
        target[column] = value
        this.dataSource = newData
      } else {
        const newData2 = {}
        newData2['purchaseDetailsId'] = key
        newData2[column] = value
        this.dataSource.push(newData2)
      }

      if (record['recNumSurplus'] <= record['recNumThis']) {
        record['recNumThis'] = record['recNumSurplus']
      } else if (record['recNumThis'] < 0) {
        record['recNumThis'] = 0
      }
    },
    saveForRecDeliReq(dataSource, supplierCodeSeleted) {
      // let jsonData = JSON.stringify(dataSource)
      // if (dataSource.length === 0) {
      //   this.$message.warn('请填写出库数量！')
      //   return
      // }
      // for (const jsonObj in dataSource) {
      //   const recNumThisData = jsonObj['recNumThis']
      //   if (recNumThisData) {
      //     this.$message.warn('请填写出库数量！')
      //     return
      //   }
      // }
      dataSource.forEach(function (data) {
        data['supplierCode'] = supplierCodeSeleted
      })

      this.axios({
        url: this.api.recDeliReq.add,
        method: 'post',
        data: dataSource,
      })
        .then((data) => {
          this.editingKey = ''
          console.log(data)
          this.$message.success('操作成功')
          this.$refs.table.refresh()
        })
        .catch(function (err) {
          if (err) {
            // me.editingKey = ''
            console.log(err)
          }
        })
    },
    cell1890ff(colum) {
      return {
        style: {
          'background-color': '#1890ff !important',
          color: 'white',
        },
      }
    },
    customHeaderCellFun(column, index) {
      // debugger
      // column.forEach((item) => {
      //   item.className = 'bk_color'
      // })
      return {
        style: {
          'background-color': '#1890ff !important',
          color: 'white',
        },
      }
    },
    handleOk(e) {
      this.confirmLoading = true
      this.saveForRecDeliReq(this.dataSource, this.supplierCodeSeleted)
      setTimeout(() => {
        this.confirmLoading = false
        this.visible = false
        this.clear_selected(0)
        this.clear_selected(1)
        this.clear_selected(2)
        this.clear_selected(3)
      }, 2000)
    },
    handleCancel(e) {
      this.visible = false
      this.clear_selected(0)
      this.clear_selected(1)
      this.clear_selected(2)
      this.clear_selected(3)
    },
    valueChange(val) {
      this.projectId = val
      this.clear_selected(1)
      this.clear_selected(2)
      this.clear_selected(3)
      this.http.get(this, {
        url: this.api.recDeliReq.getMajorPackages,
        data: {
          projectId: val,
          kind: 0,
          majorCode: '',
        },
        success(me, data) {
          if (data == undefined || data.length <= 0) {
            me.clear_selected()
          } else {
            me.majorList = data
          }
        },
      })
    },
    valueChangeMajor(val) {
      // this.projectId = val
      // this.majorList = []
      this.clear_selected(2)
      this.clear_selected(3)
      this.http.get(this, {
        url: this.api.recDeliReq.getMajorPackages,
        data: {
          projectId: this.projectId,
          kind: 1,
          majorCode: this.majorCodeSeleted,
        },
        success(me, data) {
          me.packageList = data
        },
      })
    },
    valueChangePackage(val) {
      this.clear_selected(3)
      this.http.get(this, {
        url: this.api.recDeliReq.getMajorPackages,
        data: {
          projectId: this.projectId,
          kind: 2,
          majorCode: this.majorCodeSeleted,
          packageCode: this.packageCodeSeleted,
        },
        success(me, data) {
          me.supplierList = data
        },
      })
    },
    getProjectList() {
      this.http.get(this, {
        url: this.apiBmp.bmp.projectList,
        data: {},
        success(me, data) {
          me.projectList = data
        },
      })
    },
    clear_selected(kind) {
      if (0 == kind) {
        this.projectId = ''
      } else if (1 == kind) {
        this.majorList = []
        this.majorCodeSeleted = ''
      } else if (2 == kind) {
        this.packageList = []
        this.packageCodeSeleted = ''
      } else if (3 == kind) {
        this.supplierCodeSeleted = ''
        this.supplierList = []
      }
    },
    delivery_chk(dataSource) {
      if (dataSource.length === 0) {
        this.$message.warn('请填写出库数量！')
        return false
      }
      for (const jsonObj in dataSource) {
        const recNumThisData = jsonObj['recNumThis']
        if (recNumThisData) {
          this.$message.warn('请填写出库数量！')
          return false
        }
      }
      return true
    },
  },
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.bk_color {
  background-color: #faad14 !important;
  color: white;
}
</style>
